/** SPECIAL KEYS CONSTANTS -SPECIAL STATES- */
var AT = 64    			//@
var DOT = 46			//.	
var HAT = 1
var SHARP = 35 			//#
var EXCLAMATION = 33  	//!

/** SPECIAL KEYS CONSTANTS -EXIT CONDITIONS- */
var KEY_CODE = 0;
var ENTER = 13;
var SPACE = 32

var UP = 38;
var DOWN = 40;
var BACKSPACE = 8;

//Variable of state machine
var lastState = SPACE;

//Combo vars
var currentVal = null;
var hasCombobox = false;
var dynamicComboPositionLeft = 0;

/**************************************************************************************************
 * Events
 *************************************************************************************************/

function eventAt($this, e){
	var json = searchUsers();
	renderResponse(json);		
}

function eventDot($this,e){
	var json = searchEstimates();
	renderResponse(json);
}

function eventSharp($this, e){
	var json = searchTags();
	renderResponse(json);	
}

function eventExclamation($this, e){
	var json = searchPriorities();
	renderResponse(json);	
}


function eventSpace($this, e){
	hideCombobox();
}

function eventBackspace($this, e){
	//TODO: Pensar como fazer essa parte
	hideCombobox();	
}

function eventKeyCode($this,e){
	switch(e.keyCode){
		case UP:
		case DOWN:
			moveCurrent(e.keyCode);
			break;
		default:
			console.info("Unknow event");
			break;
	}
}

function eventEnter($this, e){
	if(hasCombobox) {
		$this.val($this.val()+currentVal);
		hideCombobox();
		
		return false;
	}
	else {	
		parser($this.val());
		$('#create-histoy-detail-form').submit();	
		return false;	
	}
}

function eventDefaultState($this, e){
	//Search only with last state is null or it is not SPACE state
	if(lastState == null || lastState != SPACE){
		console.info("Event: Search");	
	}
	else {
		console.info("Event: Default");
	}
}

/**************************************************************************************************
 * Searchs
 *************************************************************************************************/

function searchUsers () {
	return '{"0":"1","1":"2","2":"3","3":"4","4":"5","5":"6","6":"7","7":"8","8":"9"}';
}

function searchTags () {
	var url = "tags";
	return request(url);
}

function searchPriorities () {
	return '{"0":"1","1":"2","2":"3","3":"4","4":"5","5":"6","6":"7","7":"8","8":"9","9":"10"}';
}

function searchEstimates () {
	return '{"0":"0","1":"1","2":"2","3":"3","4":"5","5":"8","6":"13","7":"20"}';
}

/**
 * Make a simple request to server and return an list in json format
 * 
 * @param url
 */
 function request(url){
	request_list = null;
	projectId = 1;
	
	$.ajax({
		url:  "/sprint/" + url + "/" + projectId ,
		async: false,
		success: function(data){
			request_list = data;
		}
	});
	
	return request_list;
}
/**************************************************************************************************
 * DYNAMIC MODAL
 *************************************************************************************************/

/**
 * Render a div with response of search
 * 
 * @param json formatted with values.
 */
function renderResponse(json){
	var data = JSON.parse(json);
	var $input = $("#input-search");
		
  	$.each(data, function(key, val) {
    	$input.append($(divLineTemplate(key,val)));
  	});

	var pos = $input.position().left + (dynamicComboPositionLeft * 7) + 5;
	$input.css('margin-left',pos);
	$input.show();
	
	if($input.children().size() > 0){
		hasCombobox = true;
		
		currentVal = $input.children().first().html(); 
	}  		
}

//Template that will be inserted in dynamic combo
function divLineTemplate(index,val){
	return "<div class=\"dynamic-combo "+(index==0?"current":"")+"\">"+val+"</div>";
}

/**
 * Function to hide combobox.
 *  
 */
 function hideCombobox(){
	var $search = $("#input-search");
	$search.css('margin-left',0);
	$search.hide();
	$search.empty();

	hasCombobox=false;

}

/**
 * Move current from modal
 * 
 * Function is used only when we have combobox. 
 * It change current class, UP and DOWN. 
 * 
 * @param key
 */
function moveCurrent(key){
	var $combo = $("div.dynamic-combo");
	var current = $("div.current").index();
	
	var size = $combo.size()-1;
	
	if(hasCombobox){
		if(key == UP){
			if(current <= size && current > 0){
				$($combo[current]).removeClass("current");
				currentVal = $($combo[current-1]).addClass("current").html();
			}
		}
		else{
			if(current < size && current >= 0){
				$($combo[current]).removeClass("current");
				currentVal = $($combo[current+1]).addClass("current").html();
			}
		}	
	}
}

/**************************************************************************************************
 * Parser
 *************************************************************************************************/

function parser(string){
	
	var name = "";
	var tags = "";
	var desc = "";
	var estm = null;
	
	var splitStr = string.split(" ");
	
	if(splitStr == null) return;
	
	for(var i=0;i<splitStr.length;i++){
		var str = splitStr[i];
		
		var code = str.charCodeAt(0);
		var value = str.substring(1, str.length); 
		
		switch(code){
			case SHARP:
				if(tags === "")
					tags+=value;
				else
					tags+=","+value;				
				break;
			case DOT:
				//TODO validar se e inteiro
				estm = value;
				break
			default:
				name+=str + " ";
				break;
		} 
	}
		
	//TODO: passar para outra funcao
	if(name.length > 255 ) {
		desc = name.substring(255,name.length-1);
		name = name.substring(0,255);
	}	
	$("#id_name").val(name);
	$("#id_tags").val(tags);
	$("#id_estimate").val(estm);
	$("#id_description").val(desc);
}

